import Vue from 'vue';
import Router from 'vue-router';
import iView from 'iview';
import { turnTo } from '@/libs/util';
import store from '../store';
import routes from './routes';

Vue.use(Router);

const router = new Router({
    mode: 'history',
    base: process.env.BASE_URL,
    routes,
});

// 前置导航守卫，用于完成路由导航之前
router.beforeEach((to, from, next) => {
    iView.LoadingBar.start();
    // 修改浏览器标签名
    // const title = to.meta && to.meta.title;
    // if (title) {
    //   document.title = title;
    // }
    // 获取有效期token
    const token = store.state && store.state.user && store.state.user.token;
    if (token) {
        turnTo(to, store.state.user.access, next);
        // 无匹配路由时跳转home页
        if (to.matched.length === 0) {
            next({ name: 'home' }); // 路径错跳转home页面
            // from.name ? next({ name: from.name }) : next('/login')
        } else {
            next();
        }
    } else if (to.path === '/' || to.path === '/login') {
        next();
    } else {
        next({
            path: '/',
            query: { redirect: to.fullPath }, // 将跳转的路由path作为参数，登录成功后跳转到该路由
        });
    }
});
// 后置导航守卫，用于完成路由导航之后
router.afterEach(() => {
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
});

export default router;
